package com.example.template;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname TemplateEngine
 * @Description TODO
 * @Date 2023/4/28 10:53
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class TemplateEngine {

    private static final String VAR_PATTERN = "\\$\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}";
    private static final String IF_PATTERN = "<if\\s+test=\"([a-zA-Z_][a-zA-Z0-9_]*?)\">(.*?)</if>";
    private static final Pattern VAR_REGEX = Pattern.compile(VAR_PATTERN);
    private static final Pattern IF_REGEX = Pattern.compile(IF_PATTERN, Pattern.DOTALL);

    // 解析模板并返回最终的文本
    public static String render(String template, Map<String, Object> context) {
        StringBuffer result = new StringBuffer();
        Matcher matcher = VAR_REGEX.matcher(template);

        while (matcher.find()) {
            String key = matcher.group(1);
            String value = context.getOrDefault(key, "").toString();
            matcher.appendReplacement(result, value);
        }

        matcher.appendTail(result);
        String output = result.toString();

        matcher = IF_REGEX.matcher(output);

        while (matcher.find()) {
            boolean condition = Boolean.parseBoolean(context.getOrDefault(matcher.group(1), "false").toString());
            String content = matcher.group(2);
            String replacement = condition ? content : "";
            output = output.replace(matcher.group(0), replacement);
        }

        return output;
    }


    public static void main(String[] args) {
        String template = "<p>Hello, ${name}!</p><if test=\"isAdmin\"><p>You are an admin.</p></if>";
        Map<String, Object> context = new HashMap<>();
        context.put("name", "Alice");
        context.put("isAdmin", false);
        String output = TemplateEngine.render(template, context);
        System.out.println(output); // 输出：<p>Hello, Alice!</p><p>You are an admin.</p>
    }
}
